<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form :model="queryParams" ref="queryFormRef" inline>
        <el-form-item label="公告标题" prop="zbbt">
          <el-input v-model="queryParams.zbbt" placeholder="请输入公告标题" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="招标描述" prop="zbms">
          <el-input v-model="queryParams.zbms" placeholder="请输入招标描述" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" clearable>
            <el-option
              v-for="item in [{ value: 0, label: '待激活' }, { value: 1, label: '激活' }, { value: 2, label: '归档' }]"
              :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

    </div>
    <el-card class="box-card">
      <!-- 操作工具栏 -->
      <template #header>
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增
        </el-button>
        <el-button type="danger" plain icon="Delete" :disabled="selectedIds.length === 0"
          @click="handleBatchDelete">批量删除
        </el-button>
      </template>

      <!-- 数据表格 -->
      <el-table key="id" v-loading="loading" :data="dataList" border style="width: 100%;" height="350"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" show-overflow-tooltip align="center" />
        <el-table-column label="招标编号" min-width="100" show-overflow-tooltip align="center" prop="id" />
        <el-table-column label="公告标题" min-width="100" show-overflow-tooltip align="center" prop="zbbt" />
        <el-table-column label="招标文件" min-width="100" show-overflow-tooltip align="center" prop="zbwj">
          <template #default="scope">
            <el-button v-if="scope.row.zbwj" type="primary" text
              @click="handlePreviewImages(scope.row.zbwj.split(','))">
              查看
            </el-button>
            <span v-else>暂无附件</span>
          </template>
        </el-table-column>
        <el-table-column label="招标描述" min-width="100" show-overflow-tooltip align="center" prop="zbms" />
        <el-table-column label="状态" min-width="100" show-overflow-tooltip align="center" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="info">待激活</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">激活</el-tag>
            <el-tag v-else type="danger">归档</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始日期" min-width="100" show-overflow-tooltip align="center" prop="ksrq" />
        <el-table-column label="结束日期" min-width="100" show-overflow-tooltip align="center" prop="jsrq" />
        <el-table-column label="创建时间" min-width="100" show-overflow-tooltip align="center" prop="createTime" />
        <el-table-column label="操作" min-width="200" show-overflow-tooltip align="center"
          class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-if="scope.row.status == 0 || scope.row.status == 1" type="primary" link icon="Edit"
              @click="handleUpdate(scope.row)">修改
            </el-button>
            <el-button v-if="scope.row.status == 0 || scope.row.status == 1" type="danger" link icon="Delete"
              @click="handleDelete(scope.row)">删除
            </el-button>
            <el-button v-if="scope.row.status == 0" type="primary" link @click="jihuo(scope.row)">激活
            </el-button>
            <el-button v-if="scope.row.status == 1" type="warning" link @click="closejihuo(scope.row)">取消激活
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具栏 -->
      <div class="pagination-container">
        <el-pagination background v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]" :total="total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

      <!-- 添加或修改对话框 -->
      <el-dialog v-model="open" :title="title" width="70%" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="公告标题" prop="zbbt">
            <el-input v-model="form.zbbt" placeholder="请输入公告标题" />
          </el-form-item>
          <el-form-item label="有效期" prop="time">
            <el-date-picker v-model="form.time" type="daterange" value-format="YYYY-MM-DD" @change="handleTimeChange" />
          </el-form-item>
          <el-form-item label="招标文件" prop="zbwj">
            <upload ref="uploadRef" v-model="form.zbwj" :multiple="true" :source="'album-cover'" />
          </el-form-item>
          <el-form-item label="招标描述" prop="zbms">
            <!-- <el-input v-model="form.zbms" type="textarea" placeholder="请输入招标描述" /> -->
            <mavon-editor placeholder="项目描述" style="height: 300px; width: 100%" ref="mdRef" v-model="form.zbms"
              @imgDel="imgDel" @imgAdd="imgAdd">
            </mavon-editor>
          </el-form-item>

        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog v-model="previewDialogVisible" title="图片预览" width="60%" :append-to-body="true">
        <el-carousel v-if="previewImageUrls.length > 0" height="400px">
          <el-carousel-item v-for="(url, index) in previewImageUrls" :key="index">
            <el-image :src="url" style="width: 100%; height: 100%; object-fit: contain;" fit="contain" />
          </el-carousel-item>
        </el-carousel>
        <div v-else>暂无图片</div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listSysZbApi,
  detailSysZbApi,
  deleteSysZbApi,
  addSysZbApi,
  updateSysZbApi,
  updateJh,
  updateQxJh
} from '@/api/article/zb'
import upload from '@/components/Upload/Image.vue'
import { uploadApi, deleteFileApi } from '@/api/file'

const uploadRef = ref()
// 遮罩层
const loading = ref(true)
// 选中数组
const selectedIds = ref<any[]>([])
// 总条数
const total = ref(0)
// 表格数据
const dataList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParams:any= reactive({
  pageNum: 1,
  pageSize: 10,
})

// 表单参数
const form = reactive<any>({})
// 表单校验
const rules = reactive({
  zbbt: [
    { required: true, message: "该项不能为空", trigger: "blur" }
  ],
  zbms: [
    { required: true, message: "该项不能为空", trigger: "blur" }
  ],
  time: [
    { required: true, message: "该项不能为空", trigger: "blur" }
  ],
})

const queryFormRef = ref()
const formRef = ref()

/** 查询列表 */
const getList = () => {
  loading.value = true
  const obj = {
    ...queryParams,
    zbms: queryParams.zbms == '' ? null : queryParams.zbms, // 查询条件
    zbbt: queryParams.zbbt == '' ? null : queryParams.zbbt, // 查询条件
  }
  listSysZbApi(obj).then(response => {
    dataList.value = response.data.records
    total.value = response.data.total
    loading.value = false
  })
}

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
  clearUploadFiles(); // 清空文件列表
};

/** 清空文件列表 */
const clearUploadFiles = () => {
  if (uploadRef.value && uploadRef.value.clearFiles) {
    uploadRef.value.clearFiles(); // 调用 clearFiles 方法清空文件列表
  }
};
//删除图片
function imgDel(pos: any, $file: any) {
  deleteFileApi(pos[0]).then((res) => {
    ElMessage.success('删除成功')
  })
}
//添加图片
function imgAdd(pos: any, $file: any) {
  var formdata = new FormData();
  formdata.append("file", $file);
  uploadApi(formdata, 'article-content').then((res) => {
    mdRef.value.$img2Url(pos, res.data);
  });
}
const mdRef = ref()
const videoInput = ref('')
const dialogVisible = ref(false);
/** 表单重置 */
const reset = () => {
  form.value = {
  }
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: { id: any }[]) => {
  selectedIds.value = selection.map(item => item.id)
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  title.value = "添加招标"
}

/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  reset()
  detailSysZbApi(row.id).then(response => {
    Object.assign(form, response.data)
    if (form.zbwj && form.zbwj.length > 0) {
      form.zbwj = form.zbwj.split(',')
    }
    if (form.ksrq && form.jsrq) {
      form.time = [form.ksrq, form.jsrq]
    }
    open.value = true
    title.value = "修改招标"
  })
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate((valid: any) => {
    const obj = {
      ...form
    }
    if (obj.zbwj && obj.zbwj.length > 0) {
      obj.zbwj = obj.zbwj.join(',')
    }
    if (valid) {
      if (form.id !== undefined) {
        updateSysZbApi(obj).then(response => {
          ElMessage.success("修改成功")
          cancel()
          getList()
        })
      } else {
        addSysZbApi(obj).then(response => {
          ElMessage.success("新增成功")
          cancel()
          getList()
        })
      }
    }
  })
}

/** 批量删除按钮操作 */
const handleBatchDelete = () => {
  if (!selectedIds.value.length) {
    return
  }
  ElMessageBox.confirm('是否确认删除"' + selectedIds.value.length + '"条数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteSysZbApi(selectedIds.value)
    getList()
  }).then(() => {
    getList()
    ElMessage.success("删除成功")
  })
}

/** 删除按钮操作 */
const handleDelete = (row: any) => {
  ElMessageBox.confirm('是否确认删除编号为"' + row.id + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteSysZbApi(row.id)
  }).then(() => {
    getList()
    ElMessage.success("删除成功")
  })
}


// 添加分页方法
const handleSizeChange = (val: any) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val: any) => {
  queryParams.pageNum = val
  getList()
}

/** 时间选择器改变事件 */
const handleTimeChange = (val: any) => {
  if (val.length > 0) {
    form.ksrq = val[0]
    form.jsrq = val[1]
  } else {
    form.ksrq = ''
    form.jsrq = ''
  }
}
onMounted(() => {
  getList()
})

// 控制图片预览对话框的显示
const previewDialogVisible = ref(false);
// 当前预览的图片 URL 列表
const previewImageUrls = ref<string[]>([]);

/** 预览文件（支持图片和 PDF） */
const handlePreviewImages = (fileUrls: string[]) => {
  if (!fileUrls || fileUrls.length === 0) {
    ElMessage.warning("暂无文件可预览");
    return;
  }

  // 判断文件类型
  const imageUrls = fileUrls.filter((url) => /\.(png|jpe?g|gif|bmp|webp)$/i.test(url));
  const pdfUrls = fileUrls.filter((url) => /\.pdf$/i.test(url));

  if (imageUrls.length > 0) {
    previewImageUrls.value = imageUrls;
    previewDialogVisible.value = true;
  }

  if (pdfUrls.length > 0) {
    pdfUrls.forEach((url) => {
      window.open(url, "_blank"); // 打开 PDF 文件
    });
  }
};

/**激活 */
const jihuo = (row: any) => {
  ElMessageBox.confirm(`是否确认激活?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateJh(row).then(() => {
      ElMessage.success('激活成功')
      getList()
    })
  })
}
/**取消激活 */
const closejihuo = (row: any) => {
  ElMessageBox.confirm(`是否确认取消激活?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateQxJh(row).then(() => {
      ElMessage.success('取消激活成功')
      getList()
    })
  })
}
</script>
<style scoped>
.el-table .el-table__body-wrapper {
  overflow: auto !important;
}
</style>